package com.inspiration.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.inspiration.utils.DbUtil;
import com.inspiration.utils.PathUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.Date;

/**
 * @Author : Vincent.jiao
 * @Date : 2023/11/4 16:45
 * @Version : 1.0
 */
@Component
public class DBBackup {
    @Autowired
    DataSource dataSource;

//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 0 1 * * ?")
    public void backpDB() throws FileNotFoundException, SQLException {
        backup("db_");
    }

    public void backup(String  fileName) throws FileNotFoundException {
        String suffix = fileName;

        String backupPath = PathUtils.getDBBackup();
        backupPath += File.separator + DateUtil.format(new Date(), "yyyy-MM-dd");
        File fullPathFile = new File(backupPath);
        if(fullPathFile.exists()) {
            fullPathFile.mkdirs();
        }

        HikariDataSource hikariDataSource = (HikariDataSource) dataSource;
        String password = hikariDataSource.getPassword();
        String name = hikariDataSource.getUsername();
        String url = hikariDataSource.getJdbcUrl().substring("jdbc:mysql://".length());
        String ip = url.substring(0, url.indexOf(':'));
        url = url.substring(ip.length() + 1);
        String host = url.substring(0, url.indexOf('/'));
        url = url.substring(host.length() + 1);
        String dbName = url.substring(0, url.indexOf('?'));

        String fullPath = DbUtil.exportDatabaseTool(ip, host, name, password, dbName,
                fullPathFile.getPath(),
                suffix + DateUtil.format(new Date(), "yyy-MM-dd") + ".sql");

        System.out.println("备份成功：" + fullPath);

        //图片也全部复制过去一起压缩
        FileUtil.copyFilesFromDir(new File(PathUtils.getFilePath()), fullPathFile, false);

        //开始压缩
        String zipFilePath = fullPathFile.getParentFile().getPath() + File.separator
                + suffix + DateUtil.format(new Date(), "yyy-MM-dd") + ".zip";
        ZipUtil.zip(fullPathFile.getPath(), zipFilePath);

        //删除旧有备份 .sql 文件
        FileUtil.del(fullPathFile.getPath());

        //删除多余备份，只保留1天
        for(File file : fullPathFile.getParentFile().listFiles()) {
            if(!file.getPath().contains(suffix)) {
                continue;
            }

            //跳过今天的备份
            String backupName = DateUtil.format(new Date(), "yyyy-MM-dd");
            if(file.getName().startsWith(suffix + backupName)) {
                continue;
            }

            //昨天的备份就不删 了
            backupName = DateUtil.format(new Date(System.currentTimeMillis() - 86400000 ), "yyyy-MM-dd");
            if(file.getName().startsWith(suffix + backupName)) {
                continue;
            }

            file.delete();
        }
    }
}
